import {WeaTools} from "ecCom";
import * as types from "../constants/ActionTypes";
import * as urls from "../constants/ServerUrls";
import SearchFavourite from "../util/SearchFavourite";

const {callApi} = WeaTools;

/**
 * 根据id查询收藏的信息
 * @param id
 * @returns {function(*)}
 */
export const loadForm = id => {
    let loadUrl = urls.GET_FAVOURITE;
    return dispatch => {
        callApi(loadUrl, "POST", {id}).then(resdata => {
            dispatch({
                type: types.SYSFAV_FORM_LOAD,
                data: resdata
            });

            //加载数据完成后，再打开编辑窗口，避免窗口打开后，可以看到数据修改的过程
            let params = {"1": {visible: true}};
            dispatch({
                type: types.DIALOG_SHOW_OR_HIDE,
                params
            });
        });
    }
}

/**
 * 收藏类型的变更
 * @param value
 * @returns {function(*)}
 */
export const saveForm = values => {
    let editUrl = urls.EDIT_FAVOURITE;
    let {favid, pagename, favouritetype, dirid} = values;
    return dispatch => {
        callApi(editUrl, "POST", {favid, pagename, favouritetype, dirid}).then(resdata => {
            //关闭窗口
            let params = {"1": {visible: false}};
            dispatch({
                type: types.DIALOG_SHOW_OR_HIDE,
                params
            });

            /**
             * 刷新列表
             */
            let isinit = false;
            let isreload = true;
            let searchFavourite = new SearchFavourite(dispatch);
            let paras = {isinit, isreload};
            searchFavourite.load(paras);
        });
    };
}

/**
 * 表单字段更新时，保存表单字段的值
 * @param values
 * @returns {{type: string, values: {}}}
 */
export const saveFormFields = (values = {}) => {
    let vmap = {};
    let {fields} = values;

    //将变更的字段的值，存入state中
    for (let key in fields) {
        switch (key) {
            case "pagename":
                vmap.pagename = fields[key].value;
                break;
            case "favtype":
                vmap.favouritetype = fields[key].value;
                break;
            default:
                vmap[key] = fields[key].value;
        }
    }
    return dispatch => {
        dispatch({
            type: types.SYSFAV_FORM_FIELD_CHANGE,
            values: vmap
        });
    };
}